﻿using DocBot.Objects;
using DocBot.Util;
using DocBot.Util.Collections;

using GalaSoft.MvvmLight;

using System;
using System.IO;
using System.Xml.Serialization;

namespace DocBot.ViewModel
{
	public class ChatViewModel : ViewModelBase
	{
		#region Members
		private static string configFileName = "chat.xml";
		private LocalDataBase _database = new LocalDataBase();
		ThreadSafeObservableCollection<ChatItem> _items = new ThreadSafeObservableCollection<ChatItem>();
		#endregion

		#region Properties
		public ThreadSafeObservableCollection<ChatItem> Items
		{
			get
			{
				return _items;
			}
			set
			{
				_items = value;
			}
		}
		#endregion

		#region Construction
		public ChatViewModel()
		{
			if (IsInDesignMode)
			{
				LoadChat(configFileName);
				if (_items.Count == 0)
					for (int i = 0; i < 3; ++i)
					{
						_items.Add(new ChatItem { Message = _database.GetRandomArtistName, Time = DateTime.Now, User = _database.GetRandomArtistName });
					}
			}
			else
			{
				LoadChat(configFileName);
			}
		}

		~ChatViewModel()
		{
			if (!IsInDesignMode)
				if (Settings.Instance.SaveChat)
					SaveChat(configFileName);
		}

		#endregion

		#region functions
		public void LoadChat(String configFileName)
		{
			if (File.Exists(Settings.Instance.configFilePath + "\\" + configFileName))
			{
				XmlSerializer deserializer = new XmlSerializer(typeof(ThreadSafeObservableCollection<ChatItem>));
				TextReader textReader = new StreamReader(Settings.Instance.configFilePath + "\\" + configFileName);
				ThreadSafeObservableCollection<ChatItem> _object = (ThreadSafeObservableCollection<ChatItem>)deserializer.Deserialize(textReader);
				textReader.Close();
				if (_object == null)
				{
					_object = new ThreadSafeObservableCollection<ChatItem>();
				}
				_items = _object;
			}
		}

		private void SaveChat(String configFileName)
		{
			if (_items.Count > 0)
			{
				XmlSerializer s = new XmlSerializer(typeof(ThreadSafeObservableCollection<ChatItem>));
				TextWriter writer = new StreamWriter(Settings.Instance.configFilePath + "\\" + configFileName);
				s.Serialize(writer, _items);
				writer.Close();
			}
		}

		public bool add(String user, String message)
		{
			Items.Add(new ChatItem { User = user, Time = DateTime.Now, Message = message });
			return true;
		}
		#endregion
	}
}
